<template>
  <div>
    <el-input v-model="value" readonly="true">
      <template #append>
        <el-upload
          ref="upload"
          :file-list="fileList"
          :show-file-list="false"
          :action="actionUrl"
          multiple
          :limit="1"
          accept=".xls,.xlsx"
          :on-success="submit"
          :auto-upload="false"
          :on-exceed="handleExceed"
          :on-change="handleChange"
          :headers="{ Authorization: `Bearer ${token}` }"
        >
          <el-button>浏览...</el-button>
        </el-upload>
      </template>
    </el-input>

    <el-button
      @click="handleDown"
      type="primary"
      size="small"
      link
      style="font-size: 14px; color: #007aff; margin-top: 8px"
    >
      下载批量导入模版
    </el-button>
    <div class="footer">
      <div></div>
      <div>
        <el-button class="reset-btn" @click="resetForm()">取 消</el-button>
        <el-button class="confirm-btn" @click="submitForm()"
          >确认导入</el-button
        >
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { genFileId } from "element-plus";
import storage from "../../../../../utils/storage";
import { getExportManagementBerth } from "../request.js";
const value = ref("");
const upload = ref();
const fileList = ref([]);
// const actionUrl = window.location.origin + "/user/cashier/import";
const actionUrl = "https://cipp.ecaray.com/road/berth/import";
const token = ref(storage.get("access_token") || "");
// 下载模版
const handleDown = async () => {
  await getExportManagementBerth()
    .then((res) => {
      console.log("res ===>", res);
      const fileName = extractFileNameFromHeaders(res.headers);
      const url = window.URL.createObjectURL(new Blob([res.data]));
      const link = document.createElement("a");
      link.href = url;
      link.download = fileName;
      link.click();
    })
    .catch((err) => {
      console.log("err ===>", err);
    });
};

function extractFileNameFromHeaders(headers) {
  const contentDisposition = headers.get("content-disposition") || "";

  const matches = contentDisposition.match(/filename\*=\s*utf-8''([^;]+)/);

  if (matches != null && matches[1]) {
    return decodeURIComponent(matches[1].replace('"', ""));
  }
  return "unknown-file.pdf"; // 默认文件名
}

// 获取文件路径
const handleChange = (file, fileLists) => {
  value.value = document.getElementsByClassName("el-upload__input")[0].value;
  fileList.value = fileLists;
};

const handleExceed = (files) => {
  upload.value.clearFiles();
  const file = files[0];
  file.uid = genFileId();
  upload.value.handleStart(file);
};

const submit = async (res, uploadFile, uploadFiles) => {
  console.log(res, uploadFile, uploadFiles);
  if (res.code === 0) {
    if (res.result.failCount === 0) {
      ElMessage({
        type: "success",
        message: "导入成功",
      });
      emits("operationDone");
    } else {
      ElMessage({
        type: "success",
        message: `已导入成功${res.result.successCount}条数据,失败${res.result.failCount}条数据。`,
      });
      emits("operationDone");
    }
  } else {
    ElMessage.error(res.msg);
    return;
  }
};

// 导入模版
const submitForm = () => {
  if (fileList.value.length > 0) {
    upload.value.submit();
  } else {
    alert("请选择文件后再进行导入");
  }
};

// 取消
const resetForm = () => {
  emits("operationDone");
};
const emits = defineEmits(["operationDone"]);
</script>

<style lang="less" scoped>
.footer {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
.reset-btn {
  width: 88px;
  height: 32px;
  background: #ffffff;
  border-radius: 3px;
  border: 1px solid #dcdcdc;
  font-weight: 400;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.65);
}
.confirm-btn {
  width: 88px;
  height: 32px;
  background: #007aff;
  border-radius: 3px;
  font-weight: 400;
  font-size: 14px;
  color: #ffffff;
}
</style>